package zone.czh.woi.woim.base.channel.adapter;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandler;
import io.netty.channel.ChannelOutboundHandler;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import zone.czh.woi.base.util.Pair;
import zone.czh.woi.protocol.protocol.Payload;
import zone.czh.woi.protocol.protocol.WoiProtobuf;
import zone.czh.woi.protocol.util.ProtobufPayloadUtil;

import java.util.ArrayList;
import java.util.List;
/**
*@ClassName: ProtobufAdapter
*@Description: None
*@author woi
*/
@ChannelHandler.Sharable
public class ProtobufAdapter extends ProtocolAdapter<WoiProtobuf.Payload>{

    private ProtobufDecoder protobufDecoder = new ProtobufDecoder(WoiProtobuf.Payload.getDefaultInstance());
    private ProtobufVarint32LengthFieldPrepender protobufVarint32LengthFieldPrepender = new ProtobufVarint32LengthFieldPrepender();
    private ProtobufEncoder protobufEncoder = new ProtobufEncoder();

    public ProtobufAdapter(){
        this("protobuf");
    }
    public ProtobufAdapter(String protocolName){
        super(protocolName);
    }
    @Override
    protected Payload parse(ChannelHandlerContext ctx, WoiProtobuf.Payload payload) {
        return ProtobufPayloadUtil.parse(payload);
    }

    @Override
    public Object encode(ChannelHandlerContext ctx, Payload payload) {
        return ProtobufPayloadUtil.buildPayload(payload);
    }

    @Override
    public List<Pair<String,ChannelInboundHandler>> getDecoders() {
        List<Pair<String,ChannelInboundHandler>> list = new ArrayList<>();
        list.add(new Pair<String,ChannelInboundHandler>(null,new ProtobufVarint32FrameDecoder()));
        list.add(new Pair<String,ChannelInboundHandler>(null,protobufDecoder));
        return list;
    }

    @Override
    public List<Pair<String,ChannelOutboundHandler>> getEncoders() {
        List<Pair<String,ChannelOutboundHandler>> list = new ArrayList<>();
        list.add(new Pair<String, ChannelOutboundHandler>(null,protobufVarint32LengthFieldPrepender));
        list.add(new Pair<String, ChannelOutboundHandler>(null,protobufEncoder));
        return list;
    }
}
